package com.ruoyi.api.mobileUser;

import com.google.common.collect.Lists;
import com.ruoyi.api.activiti.service.UsualWrokService;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.project.projectInfo.domain.ProjectInfo;
import com.ruoyi.project.projectInfo.service.IProjectInfoService;
import com.ruoyi.project.projectUsers.domain.ProjectUsers;
import com.ruoyi.project.projectUsers.service.IProjectUsersService;
import com.ruoyi.redis.RedisService;
import com.ruoyi.result.ResultEnum;
import com.ruoyi.result.ResultView;
import com.ruoyi.system.cache.user.UserCacheService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EnableAsync
@RestController
@Slf4j
public class MobileUserController {
  @Autowired
  private RedisService redisService;
  @Autowired
  private ISysUserService userService;
  @Autowired
  private SysPasswordService passwordService;

  @Autowired
  private UsualWrokService usualWrokService;
  @PostMapping("/api/mobileUser/register/{smscode}")
  @ResponseBody
  public ResultView register(@PathVariable @NotNull String smscode, @RequestBody @NotNull SysUser user, HttpServletRequest request) {
    if (smscode.length() < 5 && redisService.hasKey(smscode)) {//通过
      Object o = redisService.get(smscode);
      if (null == o) {
        return ResultView.error(ResultEnum.CODE_601);
      }
      if (!user.getPhonenumber().equalsIgnoreCase(String.valueOf(o))) {
        return ResultView.error(ResultEnum.CODE_602);
      }
      if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
      {
        return ResultView.error(ResultEnum.CODE_1005);
      }
      user.setUserName(user.getPhonenumber());
      user.setLoginName(user.getPhonenumber());//默认手机号码为登录号
      user.setSalt(ShiroUtils.randomSalt());
      user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
      user.setCreateBy("mobileTelRegister");
      int i = userService.insertUser(user);
      if(i > 0){
        return ResultView.ok();
      }
    }
    return ResultView.error(ResultEnum.CODE_1004);
  }

  @GetMapping("/api/login/check")
  private ResultView login(String USERNAME,String PASSWORD) {
    if(StringUtils.isEmpty(USERNAME)||StringUtils.isEmpty(PASSWORD)||PASSWORD.length()<30){
      return ResultView.error(ResultEnum.CODE_1011);
    }
    // 查询用户信息
    SysUser user = userService.selectUserByLoginName(USERNAME);
    if(user == null){
      return ResultView.error(ResultEnum.CODE_1007);
    }

    boolean matches = passwordService.matches(user, PASSWORD);
    if(!matches){
      return ResultView.error(ResultEnum.CODE_1008);
    }
    String token= Base64Utils.encodeToString((user.getUserId()+"ws"+ LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))).getBytes());
    if(redisService.set(token,user.getUserId(),3600)){
      HashMap<String,Object>map=new HashMap<>();
      map.put("token",token);
      map.put("uid",user.getUserId());//后面删掉此行
      map.put("loginName", user.getLoginName());
      map.put("userName", user.getUserName());

      List<Long> list = Lists.newArrayList();
      List<SysRole> roles = user.getRoles();
      if (roles != null && roles.size() > 0) {
        for (SysRole sysRole : roles) {
          Long roleId = sysRole.getRoleId();
          list.add(roleId);
        }
        map.put("roleIds", list.toArray());
        redisService.set(user.getUserId()+"roleId",list);//保存角色
      }
      List<SysPost> posts = user.getPosts();
      if (!posts.isEmpty()) {
        SysPost sysPost = posts.get(0);
        map.put("postName", sysPost.getPostName());
        map.put("postId", sysPost.getPostId());
      }
      return ResultView.ok(map);
    }
    return ResultView.error(ResultEnum.CODE_3);
  }


  @PostMapping("/api/mobileUser/refoundPwd/{smscode}")
  @ResponseBody
  public ResultView refoundPwd(@PathVariable @NotNull String smscode,
                               @RequestBody @NotNull SysUser user,
                               HttpServletRequest request) {
    if (smscode.length() < 5 && redisService.hasKey(smscode)) {
      Object o = redisService.get(smscode);
      if (null == o) {
        return ResultView.error(ResultEnum.CODE_601);
      }
      if (!user.getPhonenumber().equalsIgnoreCase(String.valueOf(o))) {
        return ResultView.error(ResultEnum.CODE_602);
      }
    }


    SysUser sysUser = userService.selectUserByPhoneNumber(user.getPhonenumber());
    if(sysUser == null){
      return ResultView.error(ResultEnum.CODE_1009);
    }

    sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), user.getPassword(), sysUser.getSalt()));
    int i = userService.updateUserInfo(sysUser);
    if(i > 0){
      return ResultView.ok();
    }

    return ResultView.error(ResultEnum.CODE_1004);
  }
  @PostMapping(value = "/api/avatar/upload")
  @ResponseBody
  public ResultView uploadAvatar(@RequestParam("file") MultipartFile file){
    try {
      String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file);
      return ResultView.ok(avatar);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ResultView.error(ResultEnum.OPR_FAILED);
  }
  /**
   * 递归查找孩子节点
   */
  @PostMapping(value = "/api/user/children/{pid}")
  public ResultView getChildIdsByParentId(@PathVariable Long pid){
    List<Long>rs=Lists.newArrayList();
     userService.getChildIdsByParentId(rs,pid);
     return ResultView.ok(rs);
  }
  @Autowired
  private UserCacheService userCacheService;

  @Autowired
  private IProjectUsersService projectUsersService;
  @Autowired
  private IProjectInfoService projectInfoService;
  @Autowired
  private SysUserRoleMapper userRoleMapper;
  @Autowired
  private SysUserMapper userMapper;
  @PostMapping(value = "/api/user/getGroupLeader/{uid}")
  public ResultView getAudientList(@PathVariable Long uid){
    SysUser user = userCacheService.getUserInfo(uid);
    int maxRole = usualWrokService.getProjectMaxRole(user);
    List<SysUser> rs=new ArrayList<>();
    if(maxRole == 3){
      //返回总经理
      List<SysUserRole> sysUserRoles = userRoleMapper.selectUserRoleByRoleId(110l);
      if(sysUserRoles!=null && sysUserRoles.size() >0){
        for(SysUserRole sysUserRole:sysUserRoles){
          rs.add(userCacheService.getUserInfo(sysUserRole.getUserId()));
        }
      }
      return ResultView.ok(rs);
    }

    ProjectUsers projectUsers=new ProjectUsers();
    projectUsers.setUserid(uid);

    List<ProjectUsers> puList = projectUsersService.selectProjectUsersList(projectUsers);
    if(puList!=null && puList.size() > 0){
      ProjectUsers tmp = puList.get(0);
      Long projectinfoid = tmp.getProjectinfoid();

     if(maxRole == 2){
        //返回项目经理
        ProjectInfo projectInfo =
          projectInfoService.selectProjectInfoById(projectinfoid);
        SysUser projectManager = userCacheService.getUserInfo(projectInfo.getLeaderId());
       rs.add(projectManager);
      }else{
        //返回片区管理
        Map<String,Long> map=new HashMap<>();
        map.put("roleId",115l);
        map.put("pid",projectinfoid);
        rs = userMapper.selectProjectUserByRoleId(map);
      }
      return ResultView.ok(rs);
    }else{
      return ResultView.error(-2,"功能受限！申请人不属于该项目成员");
    }

  }
}
